<template lang="html">
  <!-- 在首页父组件发送http请求,后将数据通过props传递给子组件,可减少请求次数,减少服务器压力 -->

  <div class="index">
    <selfHeader></selfHeader>

    <div class="title">
      <img src="../assets/oil.png" alt="">
      <h1>今日茶油价</h1>
      <p>{{ gameTeaoilGetData.teaOilPrice }}/kg</p>
      <div class="titleIns">
        <p>市场售出量: {{ needNum }}</p>
        <p>市场需求量: {{ sellNum }}</p>
      </div>
    </div>

    <div v-if="bigActive === 1" class="activeBox">
      <span @click="activeChange(1)" :class="active === 1 ? 'activeChoose' : ''">买入</span>
      <span @click="activeChange(3)" :class="active === 3 ? 'activeChoose' : ''">我的</span>
    </div>

    <div v-if="bigActive === 1">
      <div class="selectBox">
        <select v-if="active === 3" class="selectItem" v-model="selectItem" @change="selectFn()">
          <option :value="1">买入</option>
          <option :value="2">卖出</option>
        </select>
      </div>

      <div class="paddingBox">
        <div v-for="(item, index) in gameGoodsList.list" :key="index" class="listBox">
          <div class="userName">
            <p>{{ item.userPhone }}</p>
            <img src="../assets/zhifubao.png"/>
          </div>

          <div class="numberBox">
            <p>￥{{ item.price.toFixed(2) }}</p>
            <p>茶籽数量: {{ item.teaNum }}</p>
           <!-- <b>{{ item.start * 1 === 0 ? '未成交' : '成交' }}</b> -->
          </div>
          <img class="playImg" v-if="selectItem * 1 === 2 && active * 1 === 3 && item.playImg && item.playImg !== ''" :src='"http://114.55.102.36:8809"  + item.playImg'/>

          <div>
            <button v-if="active * 1 === 1" class="buy_play"   @click="pay(item)">购入</button>
            <button v-if="selectItem * 1 === 1 && active * 1 === 3 && item.playImg === ''" @click="moveTo(item)" class="buy_play_big">去支付</button>
            <span v-if="selectItem * 1 === 1 && active * 1 === 3 && item.playImg !== ''">已完成</span>
            <button v-if="selectItem * 1 === 2 && active * 1 === 3" @click="deletSsell(item)" class="buy_play_big">删除</button>
            <button v-if="selectItem * 1 === 2 && active * 1 === 3 && item.playImg && item.playImg !== ''" @click="gameShouKuan(item)" class="buy_play_big">确认收款</button>
          </div>
        </div>
      </div>

    </div>

    <div v-if="bigActive === 2">
      <div class="marginBox">
        <mt-field label="茶籽数量" placeholder="请输入茶籽数量" v-model="from.teaNum" @change="teaNumChange"></mt-field>
        <mt-field label="价格" :placeholder="pricePlaceholder" v-model="from.price"></mt-field>
        <mt-field label="支付密码" placeholder="请输入支付密码" v-model="from.payCode"></mt-field>

        <div class="teaNumBox">
          <span>茶籽数量: {{ gameGetData.teaNum }}</span>
          <span>手续费: {{ gameGetData.charge }}</span>
        </div>

        <button class="btn" @click='gameSell'>确认卖出</button>
      </div>
    </div>

    <div class="btnGroup">
      <span @click="bigType(1)">茶籽买入</span>
      <span @click="bigType(2)">发布售出</span>
    </div>

    <input style='display: none' ref="filElem" type="file" class="upload-file" @change="previewFile">
  </div>
</template>

<script>
import {gameGet, gameSell, gameTeaoilGet, gameSale, gameOrder, gamePlay, gameOkPlay, gameShouKuan, sellMoney, deletSsell} from '@/http/api'
import {Toast, Field, MessageBox} from 'mint-ui'
import selfHeader from '@/common/header'

export default {
  components: {
    Field,
    selfHeader,
    MessageBox
  },
  data() {
    return {
      bigActive: 1,
      user: {},
      gameGetData: {},
      from: {},
      gameTeaoilGetData: {},
      gameGoodsList: [],
      active: 1,
      gameSaleData: [],
      sellNum: 0,
      needNum: 0,
      selectItem: 1,
      uploadId: '',
      pricePlaceholder: '请输入价格'
    }
  },
  methods: {
    async teaNumChange () {
      const params = {
        uid: this.user.user.uid,
        teaNum: this.from.teaNum
      }
      const res = await sellMoney(params)
      const {minPrice, maxPrice} = res.data
      this.pricePlaceholder = `价格区间在 ${minPrice} 和 ${maxPrice}之间`
    },
    activeChange(index) {
      this.active = index * 1
      if (index * 1 === 1) {
        this.gameTeaoilGet()
      }
      // if (index * 1 === 2) {
      //   this.gameSale()
      // }
      if (index * 1 === 3) {
        this.gameOrder()
      }
    },
    async gameOrder() {
      const params = {
        uid: this.user.user.uid
      }
      const res = await gameOrder(params)
      if (res.code * 1 === 200) {
        this.gameGoodsList = res.data
      }
    },
    async gameSale() {
      const params = {
        uid: this.user.user.uid
      }
      const res = await gameSale(params)
      if (res.code * 1 === 200) {
        this.gameGoodsList = res.data
      }
    },
    bigType(index) {
      this.bigActive = index * 1
      if (index * 1 === 2) {
        this.gameGet()
      }
    },
    async gameGet() {
      const params = {
        uid: this.user.user.uid
      }
      const res = await gameGet(params)
      if (res.code * 1 === 200) {
        this.gameGetData = res.data
      }
    },
    async gameSell() {
      const params = {
        uid: this.user.user.uid,
        ...this.from
      }
      if (this.from.teaNum < 100) {
        Toast('单次出售茶籽数量不得少于100')
        return
      }
      const res = await gameSell(params)
      if (res.code * 1 === 200) {
        this.bigActive = 1
        this.gameGet()
      }
    },
    async gameTeaoilGet() {
      const res = await gameTeaoilGet({})
      if (res.code * 1 === 200) {
        this.gameTeaoilGetData = res.data.teaoilPri
        this.sellNum = res.data.sellNum
        this.needNum = res.data.needNum
        this.gameGoodsList = res.data
      }
    },
    async gameShouKuan (item) {
      console.log(item)
      const data = {
        uid: this.user.user.uid,
        id: item.id
      }
      const res = await gameShouKuan(data)
      Toast(res.message)
      this.$router.push('/')
    },
    async deletSsell (item) {
      const data = {
        uid: this.user.user.uid,
        id: item.id
      }
      const res = await deletSsell(data)
      Toast(res.message)
      this.gameSell()
    },
    selectFn() {
      this.gameGoodsList = []
      if (this.selectItem * 1 === 1) {
        this.gameOrder()
      }
      if (this.selectItem * 1 === 2) {
        this.gameSale()
      }
    },
    buy(item) {
      MessageBox.prompt('请输入交易密码').then(({value, action}) => {
        if (value) {
          if (action === 'confirm') {
            const data = {
              payCode: value.toString(),
              tid: item.id,
              uid: this.user.user.uid
            }
            gamePlay(data).then(res => {
              if (res.code * 1 === 200) {
                Toast('交易成功')
                this.bigActive = 1
                this.active = 3
              }
            })
          }
        } else {
          Toast.error('请输入交易密码')
        }
      });
    },
    buySure (url) {
      MessageBox.prompt('请输入交易密码').then(({value, action}) => {
        if (value) {
          if (action === 'confirm') {
            const data = {
              payCode: value.toString(),
              orderId: this.uploadId,
              uid: this.user.user.uid,
              playImg: url
            }
            console.log(data)
            gameOkPlay(data).then(res => {
              if (res.code * 1 === 200) {
                Toast('确认成功')
              }
            })
          }
        } else {
          Toast.error('请输入交易密码')
        }
      });
    },
    upload (item) {
      this.uploadId = item.id
      console.log(this.$refs)
      this.$refs.filElem.click()
    },
    previewFile () {
      const file = this.$refs.filElem.files[0];
      // var reader = new FileReader();
      const formData = new FormData()
      formData.append('file', file)
      const xhr = new XMLHttpRequest()
      let that = this
      xhr.onreadystatechange = function () {
        const result = JSON.parse(xhr.responseText)
        let dataUrl = result.data.path
        if (dataUrl) {
          that.buySure(dataUrl)
        }
      }
      xhr.open('POST', 'http://114.55.102.36:8809/api/shared/upload/image', true)
      xhr.send(formData)
    },
    moveTo (item) {
      this.$router.push({
        path: '/paySure',
        query: {
          type: 'buiness',
          aliplayName: item.aliplayName,
          image: item.playImg,
          id: item.id
        }
      })
    },
    pay (item) {
      this.$router.push({
        path: '/paySure',
        query: {
          type: 'teaOil',
          aliplayName: item.aliplayName,
          image: item.playImg,
          id: item.id
        }
      })
    },
  },
  created() {
    this.user = JSON.parse(localStorage.getItem('UserMessage'))
    this.gameTeaoilGet()
  }
}
</script>


<style lang="less" scoped>
@import '../assets/fz.less';
@import '../assets/index/style.css';
@import '../assets/user/icon/carstyle.css';

.index {
  margin-top: 50px;
}

.btnGroup {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;

  span {
    width: 50%;
    height: 50px;
    display: block;
    line-height: 50px;
    text-align: center;
    color: white;
  }

  span:first-child {
    background-color: #048AB9;
  }

  span:last-child {
    background-color: #80cde9;
  }
}

.activeBox {
  margin-top: 20px;
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  font-size: 18px;
  padding-bottom: 2px;

  .activeChoose {
    color: #048AB9;
    border-bottom: 2px solid #048AB9;
    font-weight: 600;
  }
}

.listBox {
  margin-bottom: 20px;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #048AB9;
  border-radius: 6px;
  overflow: hidden;
  .userName {
    display: flex;
    justify-content: space-between;
    align-items: center;
    p {
      font-size: 22px;
      color: #4caf50;
    }
    img {
      width: 28px;
      height: 28px;
    }
  }
  .numberBox {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-top: 10px;
    margin-bottom: 10px;
    font-size: 18px;
    p {
      font-size: 20px;
    }
    p:first-child {
      color: #048AB9;
    }
    p:last-child {
      font-size: 14px;
    }
  }
}

.title {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 16vw;
  position: relative;
  background-color: #f9ffea;
  padding: 10px;
  img {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 160px;
    height: 160px;
  }

  h1 {
    font-size: 18px;
  }

  p {
    font-size: 30px;
    color: #048AB9;
    font-weight: 600;
    margin-top: 16px;
  }

  .titleIns {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    margin-top: 6px;
    width: 100%;
    p {
      width: 40%;
      font-size: 16px;
      font-weight: normal;
      color: black;
    }
  }
}
.paddingBox {
  padding: 0 10px 60px;
}
.selectItem {
  margin-bottom: 20px;
  font-size: 14px;
  display: flex;
  justify-content: flex-end;
}
.teaNumBox {
  margin: 20px 16px;
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  color: #048AB9;
}
.marginBox {
  margin-top: 20px;
}

.buy_play {
  width: 60px;
  background: #048AB9;
  color: white;
  height: 30px;
  float: right;
  vertical-align: middle;
  border-radius: 6px;
  overflow: hidden;
}
.buy_play_big {
  width: 100px;
  background: #048AB9;
  color: white;
  height: 30px;
  float: right;
  vertical-align: middle;
  border-radius: 6px;
  overflow: hidden;
}
.playImg {
  width: 70%;
  display: block;
  margin: 6px auto;
}
.selectBox {
  display: flex;
  justify-content: flex-end;
  padding-right: 10px;
  box-sizing: border-box;
  width: 100%;
  select {
    width: 20%;
  }
}
</style>
